package com.teziyou.commodity.aspect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TTransport;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.teziyou.commodity.core.thrift.ConnectionManager;
import com.teziyou.commodity.service.SceneService;
import com.teziyou.commodity.service.TicketService;
import com.teziyou.commodity.util.Lang;
import com.teziyou.commodity.util.Maps;

@SuppressWarnings("rawtypes")
@Component
@Aspect
public class ThriftExceptionAspect {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ThriftExceptionAspect.class);
	
	public static final Map specialMap = Maps.newHashMap(SceneService.class, "ScenicSpotInfoService"
			, TicketService.class, "TicketInfoService");
	
	public ThriftExceptionAspect() {
		//System.out.println("切面初始化...");
	}
	
	@Pointcut("execution(* com.teziyou.commodity.service.*.*(..))")
	public void pointcut() {
		
	}
	
	@Around("pointcut()")
	public Object doAround(ProceedingJoinPoint pjp) {
		//System.out.println(pjp.getSignature().getName());
		Object result = null;
		TTransport transport = null;
		try {
			Object target = pjp.getTarget();
			Class clazz = target.getClass();
			//System.out.println(clazz);
			
			
			Field cmField = clazz.getDeclaredField("connectionManager");
			
			//Field field = clazz.getField("connectionManager");
			cmField.setAccessible(true);
			
			ConnectionManager connectionManager = (ConnectionManager) cmField.get(target);
			transport = connectionManager.getTransport();
			
			Field cField = clazz.getDeclaredField("client");
			cField.setAccessible(true);
			
			/**
			 *  TProtocol protocol = new TCompactProtocol(transport);
		        // TProtocol protocol = new TJSONProtocol(transport);
		        client = new DictionaryService.Client(protocol);
			 */
			TProtocol protocol = new TCompactProtocol(transport);
			if(specialMap.containsKey(clazz)) {
				//System.err.println("王瑜迪写的烂方法");
				//System.out.println(specialMap.get(clazz));
				protocol = new TMultiplexedProtocol(protocol, Lang.toString(specialMap.get(clazz)));
			}
			Constructor con = cField.getType().getConstructor(TProtocol.class);
			cField.set(target, con.newInstance(protocol));
			if(!transport.isOpen()) transport.open();
			result = pjp.proceed();
			return result;
		} catch (Throwable e) {
			e.printStackTrace();
			logger.error(e);
			return null;
		} finally {
			transport.close();
		}
	}
	
}